package com.qf.fmall2302.order.controller;

import com.qf.fmall2302.order.entity.Orders;
import com.qf.fmall2302.order.service.IOrdersService;
import com.qf.fmall2302.utils.FmallConstants;
import com.qf.fmall2302.vo.ResultVo;
import com.qf.fmall2302.websocket.OrderWebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.function.Function;

/**
 * <p>
 * 订单  前端控制器
 * </p>
 *
 * @author dongjl
 * @since 2023-08-24
 */
@RestController
@RequestMapping("/order")
@CrossOrigin
@Slf4j
public class OrdersController {

    @Autowired
    IOrdersService ordersService;

    /**
     * 模拟微信支付的回调接口
     * @param orderid
     * @return
     * @throws IOException
     */
    @GetMapping("/wxcallback/{orderid}")
    public ResultVo wxcallback(@PathVariable("orderid") String orderid) throws IOException {

        // 把数据库中的订单状态为该 已支付状态

        // 给该orderid打开的浏览器页面，主动推送一个消息
        OrderWebSocketServer.pushMsg(orderid,"1");

        return ResultVo.ok(FmallConstants.SUCCESS_CODE, FmallConstants.SUCCESS_MSG, "ok");
    }


    @GetMapping("/status/{orderid}")
    public ResultVo status(@PathVariable("orderid") String orderid){

        log.info("入参为:orderid={}", orderid);

        String data = ordersService.status(orderid);

        return ResultVo.ok(FmallConstants.SUCCESS_CODE, FmallConstants.SUCCESS_MSG, data);

    }

    @PostMapping("/add")
    public ResultVo add(String cids,@RequestBody Orders orders) throws Exception {

        log.info("入参为:cids={},orders={}", cids);

        if (cids.contains("#")){
            cids= cids.replaceAll("#","");
        }

        String[] split = cids.split(",");

        Integer[] intArray = Arrays.stream(split)
                             .map(Integer::parseInt)
                             .toArray(Integer[]::new);

        HashMap<String,Object> data = ordersService.addOrder(intArray,orders);

        return ResultVo.ok(FmallConstants.SUCCESS_CODE, FmallConstants.SUCCESS_MSG, data);
    }




}
